import { defineStore } from 'pinia'

export type Role = 'admin' | 'editor' | 'viewer'

export interface Account {
  id: number
  username: string
  password: string
  role: Role
  avatar?: string | null
}

interface UserState {
  token: string | null
  name: string | null
  role: Role | null
  users: Account[]
  avatar: string | null
}

const USERS_KEY = 'users'
const TOKEN_KEY = 'token'
const CURRENT_KEY = 'currentUser'

function loadUsers(): Account[] {
  const raw = localStorage.getItem(USERS_KEY)
  if (raw) return JSON.parse(raw)
  const seed: Account[] = [
    { id: 1, username: 'admin', password: 'admin123', role: 'admin', avatar: null },
    { id: 2, username: 'editor', password: 'editor123', role: 'editor', avatar: null }
  ]
  localStorage.setItem(USERS_KEY, JSON.stringify(seed))
  return seed
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: null,
    name: null,
    role: null,
    users: [],
    avatar: null
  }),
  actions: {
    saveUsers() {
      localStorage.setItem(USERS_KEY, JSON.stringify(this.users))
    },
    setToken(token: string | null) {
      this.token = token
      if (token) localStorage.setItem(TOKEN_KEY, token)
      else localStorage.removeItem(TOKEN_KEY)
    },
    setCurrent(name: string | null, role: Role | null) {
      this.name = name
      this.role = role
      const user = this.users.find(u => u.username === name)
      this.avatar = user?.avatar || null
      if (name && role) {
        localStorage.setItem(CURRENT_KEY, JSON.stringify({ name, role, avatar: this.avatar }))
      } else {
        localStorage.removeItem(CURRENT_KEY)
      }
    },
    hydrate() {
      this.users = loadUsers()
      const token = localStorage.getItem(TOKEN_KEY)
      const current = localStorage.getItem(CURRENT_KEY)
      if (token) this.token = token
      if (current) {
        const data = JSON.parse(current)
        this.name = data.name
        this.role = data.role
        this.avatar = data.avatar || null
      }
    },
    async register(username: string, password: string, role: Role = 'viewer') {
      if (!username || !password) throw new Error('用户名和密码不能为空')
      const exists = this.users.some(u => u.username === username)
      if (exists) throw new Error('用户名已存在')
      const id = Math.max(0, ...this.users.map(u => u.id)) + 1
      this.users.push({ id, username, password, role, avatar: null })
      this.saveUsers()
      return true
    },
    async login(username: string, password: string) {
      const user = this.users.find(u => u.username === username && u.password === password)
      if (!user) return false
      this.setToken('local-token')
      this.setCurrent(user.username, user.role)
      return true
    },
    logout() {
      this.setToken(null)
      this.setCurrent(null, null)
    },
    // Admin operations
    createUser(account: Omit<Account, 'id'>) {
      const id = Math.max(0, ...this.users.map(u => u.id)) + 1
      this.users.push({ id, ...account })
      this.saveUsers()
    },
    updateUser(id: number, patch: Partial<Omit<Account, 'id'>>) {
      const idx = this.users.findIndex(u => u.id === id)
      if (idx >= 0) {
        this.users[idx] = { ...this.users[idx], ...patch }
        this.saveUsers()
        if (this.users[idx].username === this.name) {
          this.avatar = this.users[idx].avatar || null
          localStorage.setItem(CURRENT_KEY, JSON.stringify({ name: this.name, role: this.role, avatar: this.avatar }))
        }
      }
    },
    removeUser(id: number) {
      this.users = this.users.filter(u => u.id !== id)
      this.saveUsers()
    },
    changePassword(username: string, oldPwd: string, newPwd: string) {
      const user = this.users.find(u => u.username === username)
      if (!user) throw new Error('用户不存在')
      if (user.password !== oldPwd) throw new Error('原密码错误')
      user.password = newPwd
      this.saveUsers()
    },
    setAvatar(username: string, dataUrl: string | null) {
      const u = this.users.find(x => x.username === username)
      if (!u) return
      u.avatar = dataUrl
      this.saveUsers()
      if (this.name === username) {
        this.avatar = dataUrl
        localStorage.setItem(CURRENT_KEY, JSON.stringify({ name: this.name, role: this.role, avatar: this.avatar }))
      }
    }
  }
})


